import fs from 'fs';
import { relative, resolve, sep } from 'node:path';

const entryPrefix = './node_modules/monaco-editor/esm/vs';

export default function () {
  return {
    name: 'rollup-plugin-monaco-locale-inject',
    load(moduleId) {
      const nlsEnd = `${sep}nls.js`;
      const testEnd = `${sep}editorOptions.js`;
      const breakEnd = `${sep}inject-css.js`;
      if (moduleId.endsWith(nlsEnd)) {
        return fs.readFileSync(resolve('./src/nls.js')).toString();
      }
      // if (moduleId.endsWith(breakEnd)) {
      //   process.exit(1);
      //   // console.log(this.getModuleInfo(moduleId));
      // }
      return null; // 其他ID应按通常方式处理
    },
    transform(code, id) {
      if (code.includes('../nls')) {
        const row = /^(import\s+.*nls(.js)?[\'\"];?)$/gim.exec(code);
        const nlsId = relative(entryPrefix, id)
          // replace extname
          .replace(/.js$/, '')
          // replace window sep to http sep
          .replace(/\\/gm, '/');
        if (row != null) {
          const [head, ...tail] = code.split(row[0]);
          const source = row[0].replace(
            /import[\s]+(.*)[\s]+from[\s]+([\'\"])([^\'\"]+)\2;?/gm,
            ($0, $1, $2, $3) => {
              return [
                `import { createLocalize } from '${$3}';`,
                $1.trimStart().startsWith('*')
                  ? `const nls = createLocalize('${nlsId}');`
                  : `const ${$1} = createLocalize('${nlsId}');`,
              ].join('\n');
            },
          );
          return [head, source, ...tail].join('\n');
        }
      }
      return code;
    },
  };
}
